package com.tianhe.visitormanagement.server.common;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @Author ：史乐
 * @Date ：Created in 15:13 2022/3/5
 */
@Slf4j
@Data
@Component
public  class UdpHandlerAbstract extends SimpleChannelInboundHandler<DatagramPacket> {

    /** 空闲次数 */
    private int idle_count =1;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        ByteBuf buf = packet.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String[] strings = bytesToHexStringArr(req);
        String body = strings.toString();
        System.out.println(body);//打印收到的信息
        //向客户端发送消息
        String json = "来自服务端: 南无阿弥陀佛";
        // 由于数据报的数据是以字符数组传的形式存储的，所以传转数据
        byte[] bytes = json.getBytes("UTF-8");
        DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), packet.sender());
        ctx.writeAndFlush(data);//向客户端发送消息
    }


    /**
     * 字节数组转16进制字符串数组
     */
    public static String[] bytesToHexStringArr(byte[] bArr) {
        if (bArr == null) {
            return null;
        }
        String[] strs = new String[bArr.length];
        String sTmp;

        for (int i = 0; i < bArr.length; i++) {
            sTmp = Integer.toHexString(0xFF & bArr[i]);
            if (sTmp.length() < 2) {
                strs[i] = StringUtils.join("0", sTmp);
            } else {
                strs[i] = sTmp;
            }
        }

        return strs;
    }
}
